library(plyr)
library(foreign)
library(apsrtable)
library(AER)

######
##Estimating Effect of Issue Frames on Opinion
######

load('qualtrics.framing.opinion.RData')
load('mturk.framing.opinion.RData')
load('tess.framing.opinion.RData')

mturk.framing.opinion <- mturk.framing.opinion[,c('id','frame','opinion','issue','survey')]
qualtrics.framing.opinion <- qualtrics.framing.opinion[,c('id','frame','opinion','policy','survey')]
names(qualtrics.framing.opinion) <- c('id','frame','opinion','issue','survey')
names(tess.framing.opinion) <- c('id','frame','opinion','issue','survey')

framing.opinion.combined <- rbind(mturk.framing.opinion,qualtrics.framing.opinion,tess.framing.opinion)
framing.opinion.combined$id <- paste(framing.opinion.combined$survey,'-',framing.opinion.combined$id,sep='')
framing.opinion.combined$issuebysurvey <- paste(framing.opinion.combined$issue,'-',framing.opinion.combined$survey,sep='')
framing.opinion.combined <- framing.opinion.combined[!is.na(framing.opinion.combined$opinion) & !is.na(framing.opinion.combined$frame),]

framing.effect.out <- function(issue){
	frame.mod <- lm(opinion~frame,data=framing.opinion.combined[framing.opinion.combined$issuebysurvey==issue,])
	return(c(frame.mod$coefficients[2],sqrt(vcov(frame.mod)[2,2]),frame.mod$coefficients[2]-2*sqrt(vcov(frame.mod)[2,2]),frame.mod$coefficients[2]+2*sqrt(vcov(frame.mod)[2,2])))
}

issue.survey.list <- unique(framing.opinion.combined$issuebysurvey)
framing.effect.opinion.out <- as.data.frame(t(sapply(X=issue.survey.list,FUN=framing.effect.out)))
names(framing.effect.opinion.out) <- c('framing.effect.opinion.point','framing.effect.opinion.se','framing.effect.opinion.lower.ci','framing.effect.opinion.upper.ci')

######
##Estimating Effect of Issue Frames on Candidate Choice
######

load('qualtrics.framing.vote.RData')
load('mturk.framing.vote.RData')
load('tess.framing.vote.RData')
tess.framing.vote <- tess.framing.vote[,c('id','issue','frame.agree','issue.agree','candidate.selected','survey','choice.number','party.contrast','issue.contrast')]
tess.framing.vote$choice.number <- as.numeric(as.character(mapvalues(x=tess.framing.vote$choice.number,from=c('choice1','choice2','choice3','choice4'),to=c(1,2,3,4))))
names(tess.framing.vote) <- c('id','issue','frame.agree','issue.agree','candidate.selected','survey','choice.number','party.contrast','issue.contrast')

mturk.framing.vote <- mturk.framing.vote[,c('id','issue','frame.agree','issue.agree','chose.candidate','survey','choice','profile.type','issue.contrast')]
mturk.framing.vote$choice <- as.numeric(as.character(mapvalues(x=mturk.framing.vote$choice,from=c('choice1','choice2','choice3','choice4','choice5','choice6','choice7','choice8'),to=c(1,2,3,4,5,6,7,8))))
mturk.framing.vote$profile.type <- as.numeric(as.character(mapvalues(x=mturk.framing.vote$profile.type,from=c('Same Party','Different Party'),to=c(0,1))))
names(mturk.framing.vote) <- c('id','issue','frame.agree','issue.agree','candidate.selected','survey','choice.number','party.contrast','issue.contrast')

qualtrics.framing.vote <- qualtrics.framing.vote[,c('id','issue','frame.agree','issue.agree','chose.candidate','survey','choice.number','party.type','issue.contrast')]
qualtrics.framing.vote$choice.number <- as.numeric(as.character(mapvalues(x=qualtrics.framing.vote$choice.number,from=c('issue.choice1','issue.choice2','issue.choice3','issue.choice4'),to=c(1,2,3,4))))
qualtrics.framing.vote$party.type <- as.numeric(as.character(mapvalues(x=qualtrics.framing.vote$party.type,from=c('primary','general'),to=c(0,1))))

names(qualtrics.framing.vote) <- c('id','issue','frame.agree','issue.agree','candidate.selected','survey','choice.number','party.contrast','issue.contrast')
framing.vote.combined <- rbind(mturk.framing.vote,qualtrics.framing.vote,tess.framing.vote)

framing.vote.combined$id <- paste(framing.vote.combined$survey,'-',framing.vote.combined$id,sep='')
framing.vote.combined$issuebysurvey <- paste(framing.vote.combined$issue,'-',framing.vote.combined$survey,sep='')
framing.vote.combined <- framing.vote.combined[!is.na(framing.vote.combined$candidate.selected) & !is.na(framing.vote.combined$frame.agree),]

fit.w.robust <- function(model, cluster.var, dta){	
	robust.se <- function(model, cluster){
		require(sandwich)
		require(lmtest)
		M <- length(unique(cluster))
		N <- length(cluster)
		K <- model$rank
		dfc <- (M/(M - 1)) * ((N - 1)/(N - K))
		uj <- apply(estfun(model), 2, function(x) tapply(x, cluster, sum));
		rcse.cov <- dfc * sandwich(model, meat = crossprod(uj)/N)
		rcse.se <- coeftest(model, rcse.cov)
		return(list(rcse.cov, rcse.se))
	}
	
	out <- model$model
	clustervar <- mapply(paste,cluster.var,dta[!(1:dim(dta)[1] %in% model$na.action),cluster.var],sep="")
	vcov <- robust.se(model, clustervar)
	model$se <- vcov[[1]]
	model$coeftest <- vcov[[2]]
	return(model)
}

framing.effect.out.vote <- function(issue){
	frame.mod <- lm(candidate.selected~frame.agree,data=framing.vote.combined[framing.vote.combined$issuebysurvey==issue,])
	frame.mod <- fit.w.robust(frame.mod,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurvey==issue,])
	return(c(frame.mod$coefficients[2],sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]-2*sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]+2*sqrt(frame.mod$se[2,2])))
}

framing.effect.vote.out <- as.data.frame(t(sapply(X=issue.survey.list,FUN=framing.effect.out.vote)))
names(framing.effect.vote.out) <- c('framing.effect.vote.point','framing.effect.vote.se','framing.effect.vote.lower.ci','framing.effect.vote.upper.ci')

#Visualization
combined.plot.frame <- cbind.data.frame(framing.effect.opinion.out,framing.effect.vote.out)
combined.plot.frame$issue <- lapply(strsplit(rownames(combined.plot.frame),split="-",fixed=TRUE),'[[',1)
combined.plot.frame$issue <- gsub(pattern=" Policy",replacement="",x=combined.plot.frame$issue,fixed=TRUE)
combined.plot.frame$sample <- lapply(strsplit(rownames(combined.plot.frame),split="-",fixed=TRUE),'[[',2)
combined.plot.frame$study <- NA
combined.plot.frame$study[which(combined.plot.frame$sample=="mturk")] <- 'Study 1'
combined.plot.frame$study[which(combined.plot.frame$sample=="qualtrics")] <- 'Study 2'
combined.plot.frame$study[which(combined.plot.frame$sample=="tess")] <- 'Study 3'

combined.plot.frame <- combined.plot.frame[order(combined.plot.frame$study,-rank(combined.plot.frame$framing.effect.opinion.point),decreasing=TRUE),]

#Visualization
pdf(file="frame-issuevoting.pdf",height=6,width=6)
par(mar=c(4,4.75,1,4))
plot(x=combined.plot.frame$framing.effect.opinion.point,y=1:length(combined.plot.frame$framing.effect.opinion.point)+.175,xlim=c(-.1,.3),ylim=c(.9,11.1),pch=16,yaxt='n',ylab='',xlab='Effect of Issue Frame on Outcome')
abline(v=0,lty=2,col='gray80',lwd=2)
points(x=combined.plot.frame$framing.effect.vote.point,y=1:length(combined.plot.frame$framing.effect.opinion.point)-.175,pch=16,col='gray50')

axis(side=2,at=1:length(combined.plot.frame$framing.effect.opinion.point),las=1,labels=combined.plot.frame$issue,tick=FALSE,line=-.75)
axis(side=4,at=c(1.5,3.5,8),las=1,labels=c("Study 3","Study 2","Study 1"),tick=FALSE,line=-.75)

segments(x0=rep(-.5,times=length(combined.plot.frame$framing.effect.opinion.point)),x1=rep(.5,times=length(combined.plot.frame$framing.effect.opinion.point)),y0=1:length(combined.plot.frame$framing.effect.opinion.point)+.5,lwd=.5,col='gray70')

segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(2.5,4.5),lwd=2)

segments(x0=combined.plot.frame$framing.effect.opinion.lower.ci,x1=combined.plot.frame$framing.effect.opinion.upper.ci,y0=1:length(combined.plot.frame$framing.effect.opinion.point)+.175,lwd=2)
segments(x0=combined.plot.frame$framing.effect.vote.lower.ci,x1=combined.plot.frame$framing.effect.vote.upper.ci,y0=1:length(combined.plot.frame$framing.effect.opinion.point)-.175,lwd=2,col='gray50')

text(y=8.35,x=combined.plot.frame$framing.effect.opinion.point[8]+.004,label='Policy Opinion',cex=.68)
text(y=8.045,x=combined.plot.frame$framing.effect.vote.point[8],label='Candidate Choice',cex=.68)
dev.off()

######
##Estimating Relationship Between Framing Effects and Issue Agreement Effects
######

issue.effect.out.vote <- function(issue){
	frame.mod <- lm(candidate.selected~issue.agree,data=framing.vote.combined[framing.vote.combined$issuebysurvey==issue,])
	frame.mod <- fit.w.robust(frame.mod,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurvey==issue,])
	return(c(frame.mod$coefficients[2],sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]-2*sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]+2*sqrt(frame.mod$se[2,2])))
}

issue.agreement.vote.out <- as.data.frame(t(sapply(X=issue.survey.list,FUN=issue.effect.out.vote)))
names(issue.agreement.vote.out) <- c('issue.agreement.vote.point','issue.agreement.vote.se','issue.agreement.vote.lower.ci','issue.agreement.vote.upper.ci')

combined.frame.issue.weight <- cbind.data.frame(framing.effect.opinion.out,issue.agreement.vote.out)
combined.frame.issue.weight$issue <- lapply(strsplit(rownames(combined.frame.issue.weight),split="-",fixed=TRUE),'[[',1)
combined.frame.issue.weight$issue <- gsub(pattern=" Policy",replacement="",x=combined.frame.issue.weight$issue,fixed=TRUE)
combined.frame.issue.weight$sample <- lapply(strsplit(rownames(combined.frame.issue.weight),split="-",fixed=TRUE),'[[',2)
combined.frame.issue.weight$study <- NA
combined.frame.issue.weight$study[which(combined.frame.issue.weight$sample=="mturk")] <- 'Study 1'
combined.frame.issue.weight$study[which(combined.frame.issue.weight$sample=="qualtrics")] <- 'Study 2'
combined.frame.issue.weight$study[which(combined.frame.issue.weight$sample=="tess")] <- 'Study 3'
combined.frame.issue.weight$issue[which(combined.frame.issue.weight$issue=="Education")[1]] <- 'Education-1'
combined.frame.issue.weight$issue[which(combined.frame.issue.weight$issue=="Education")[1]] <- 'Education-2'
combined.frame.issue.weight$issue[which(combined.frame.issue.weight$issue=="Education")[1]] <- 'Education-3'
combined.frame.issue.weight$issue[which(combined.frame.issue.weight$issue=="Trade")[1]] <- 'Trade-1'
combined.frame.issue.weight$issue[which(combined.frame.issue.weight$issue=="Trade")[1]] <- 'Trade-2'
combined.frame.issue.weight$issue[which(combined.frame.issue.weight$issue=="Trade")[1]] <- 'Trade-3'

pdf(file="frame-issueweight-all.pdf",height=4,width=6)
par(mar=c(4,4,2,2))
plot(x=combined.frame.issue.weight$issue.agreement.vote.point,y=combined.frame.issue.weight$framing.effect.opinion.point,pch=16,ylim=c(-.025,.275),xlim=c(.2,.5),las=1,xlab="Issue Weight in Candidate Preferences",ylab="Framing Effect on Issue")
abline(lm(combined.frame.issue.weight$framing.effect.opinion.point ~ combined.frame.issue.weight$issue.agreement.vote.point),lwd=3,col=rgb(0,0,0,alpha=.15))
text(x=combined.frame.issue.weight$issue.agreement.vote.point,y=combined.frame.issue.weight$framing.effect.opinion.point, labels=combined.frame.issue.weight$issue, cex=.7,pos=c(3,3,4,3,1,3,3,2,1,1,1))
dev.off()

study1.comp <- subset(combined.frame.issue.weight,combined.frame.issue.weight$study=="Study 1")
study1.comp$issue <- gsub(x=study1.comp$issue,pattern="-1",replacement="")

pdf(file="frame-issueweight-study1.pdf",height=4,width=6)
par(mar=c(4,4,2,2))
plot(x=study1.comp$issue.agreement.vote.point,y=study1.comp$framing.effect.opinion.point,pch=16,ylim=c(-.025,.29),xlim=c(.25,.5),las=1,xlab="Issue Weight in Candidate Choice",ylab="Issue Framing Effect on Policy Opinion")
abline(lm(study1.comp$framing.effect.opinion.point ~ study1.comp$issue.agreement.vote.point),lwd=3,col=rgb(0,0,0,alpha=.15))
text(x=study1.comp$issue.agreement.vote.point,y=study1.comp$framing.effect.opinion.point, labels=study1.comp$issue, cex=,9,pos=c(1,3,1,3,1,1,3))
segments(x0=study1.comp$issue.agreement.vote.point,y0=study1.comp$framing.effect.opinion.upper.ci,y1=study1.comp$framing.effect.opinion.lower.ci,col=rgb(0,0,0,alpha=.15),lwd=2)
segments(x0=study1.comp$issue.agreement.vote.upper.ci,x1=study1.comp$issue.agreement.vote.lower.ci,y0=study1.comp$framing.effect.opinion.point,col=rgb(0,0,0,alpha=.15),lwd=2)
dev.off()

combined.frame.issue.weight$issue.type <- NA
combined.frame.issue.weight$issue.type[combined.frame.issue.weight$issue %in% c('Spending','Immigration','Security','Trade-1','Trade-2','Trade-3')] <- 'prior'
combined.frame.issue.weight$issue.type[combined.frame.issue.weight$issue %in% c('Marriage','Abortion','Security','Education-1','Education-2','Education-3')] <- 'new'

#All
all.frame.weight.comp <- lm(framing.effect.opinion.point ~ issue.agreement.vote.point,data=combined.frame.issue.weight)

#Study 1 only
study.1.comparison <- lm(framing.effect.opinion.point ~ issue.agreement.vote.point,data=combined.frame.issue.weight,subset=which(issue %in% c('Spending','Immigration','Security','Trade-1','Marriage','Abortion','Education-1')))

##Study 1 only - prior
study.1.comparison <- lm(framing.effect.opinion.point ~ issue.agreement.vote.point,data=combined.frame.issue.weight,subset=which(issue %in% c('Spending','Immigration','Security','Trade-1','Marriage','Abortion','Education-1')))

##
cor.test(x=study1.comp$framing.effect.opinion.point,y=study1.comp$issue.agreement.vote.point)
cor.test(x=study1.comp$framing.effect.opinion.point[which(study1.comp$issue %in% c('Spending','Immigration','Security','Trade'))],y=study1.comp$issue.agreement.vote.point[which(study1.comp$issue %in% c('Spending','Immigration','Security','Trade'))])

#Only Prior Published Frames
prior.frame.weight.comp <- lm(framing.effect.opinion.point ~ issue.agreement.vote.point,data=combined.frame.issue.weight,subset=which(issue %in% c('Spending','Immigration','Security','Trade-1','Trade-2','Trade-3')))

#Only New Frames
new.frame.weight.comp <- lm(framing.effect.opinion.point ~ issue.agreement.vote.point,data=combined.frame.issue.weight,subset=which(issue %in% c('Marriage','Abortion','Education-1','Education-2','Education-3')))

apsrtable(all.frame.weight.comp,study.1.comparison,prior.frame.weight.comp,new.frame.weight.comp,model.names=c('All Issues/Studies','Only Study 1','Only Previously Published Frames','Only New Frames'),caption="Regression of Framing Effect Magnitude on Issue Weight in Candidate Choice")

cor.test(x=combined.frame.issue.weight$framing.effect.opinion.point,y=combined.frame.issue.weight$issue.agreement.vote.point)

cor.test(x=combined.frame.issue.weight$framing.effect.opinion.point[which(combined.frame.issue.weight$issue %in% c('Spending','Immigration','Security','Trade-1','Trade-2','Trade-3'))],y=combined.frame.issue.weight$issue.agreement.vote.point[which(combined.frame.issue.weight$issue %in% c('Spending','Immigration','Security','Trade-1','Trade-2','Trade-3'))])

cor.test(x=combined.frame.issue.weight$framing.effect.opinion.point[which(combined.frame.issue.weight$issue %in% c('Spending','Immigration','Security','Trade-1'))],y=combined.frame.issue.weight$issue.agreement.vote.point[which(combined.frame.issue.weight$issue %in% c('Spending','Immigration','Security','Trade-1'))])

######
##Framing Carry-over in general
######

#Cluster bootstrap to account for repeated issues/votes for each individual

all.ids <- unique(framing.opinion.combined$id)

#Id list that indexes id numbers to row numbers in combined data frame
id.list.vote <- list()
id.list.opinion <- list()

for(k in 1:length(all.ids)){
	id.list.vote[[as.character(all.ids)[k]]] <- which(framing.vote.combined$id==unique(all.ids)[k])
	id.list.opinion[[as.character(all.ids)[k]]] <- which(framing.opinion.combined$id==unique(all.ids)[k])
}

#Function to return the rows associated with a given id number for respondent cluster bootstrap
out.rows.vote <- function(entry){
	return(unlist(id.list.vote[[entry]]))
}

out.rows.opinion <- function(entry){
	return(unlist(id.list.opinion[[entry]]))
}

carry.over.boot <- NA

set.seed(seed=3328)
for(k in 1:2000){
	#Generating Bootstrap Dataset
	keep.ids <- sample(x=as.character(all.ids), size=length(all.ids), replace=TRUE)
	
	boot.rows.vote <- as.vector(unlist(sapply(X=keep.ids,FUN=out.rows.vote)))
	boot.rows.opinion <- as.vector(unlist(sapply(X=keep.ids,FUN=out.rows.opinion)))
	
	boot.dta.vote <- framing.vote.combined[boot.rows.vote,]
	boot.dta.opinion <- framing.opinion.combined[boot.rows.opinion,]
	
	frame.vote.boot <- lm(candidate.selected ~ frame.agree + factor(issuebysurvey),data=boot.dta.vote)
	frame.issue.boot <- lm(opinion ~ frame + factor(issuebysurvey),data=boot.dta.opinion)
	carry.over.boot[k] <- frame.vote.boot$coefficients[2]/frame.issue.boot$coefficients[2]
}
	
frame.vote.all <- lm(candidate.selected ~ frame.agree + factor(issuebysurvey),data=framing.vote.combined)
frame.issue.all <- lm(opinion ~ frame + factor(issuebysurvey),data=framing.opinion.combined)
carry.over.all <- frame.vote.all$coefficients[2]/frame.issue.all$coefficients[2]
carry.over.ses <- quantile(carry.over.boot,probs=c(.025,.975))
carry.over.all;carry.over.ses

######
##Estimating Effects of Issue Frames on Candiate Preferences Relative to other candidate traits
######

#TESS (Study 3)
load('tess.candidate.features.RData')

tess.independent.vars <- c('copartisan','candidate.gender','candidate.profession','trade.issue.agree','education.issue.agree','trade.frame.agree','education.frame.agree')
tess.candidate.features$candidate.gender <- relevel(x=tess.candidate.features$candidate.gender,ref='Male')
tess.candidate.features$candidate.profession <- relevel(x=tess.candidate.features$candidate.profession,ref='Car dealer')

trait.effect.out.vote <- function(dta,candidate.trait){
	store.frame.outer <- as.data.frame(matrix(data=NA,ncol=4,nrow=1))
	names(store.frame.outer) <- c('variable.type','variable.level','effect','se')
	
	for(k in 1:length(candidate.trait)){
		model <- as.formula(paste('candidate.selected~',candidate.trait[k],sep=''))
		trait.mod <- lm(formula=model,data=dta)
		trait.mod <- fit.w.robust(trait.mod,cluster.var='id',dta=dta)
		coefs <- trait.mod$coefficients[2:length(trait.mod$coefficients)]
		coef.names <- names(trait.mod$coefficients)[2:length(trait.mod$coefficients)]
		coef.ses <- sqrt(diag(trait.mod$se))[2:length(trait.mod$coefficients)]
		store.frame.inner <- cbind.data.frame(rep(candidate.trait[k],length(coefs)),coef.names,coefs,coef.ses)
		names(store.frame.inner) <- c('variable.type','variable.level','effect','se')
		store.frame.outer <- rbind(store.frame.outer,store.frame.inner)
	}
	store.frame.outer <- store.frame.outer[-1,]
	store.frame.outer$effect.lower.ci <- store.frame.outer$effect - 2*store.frame.outer$se
	store.frame.outer$effect.upper.ci <- store.frame.outer$effect + 2*store.frame.outer$se
	return(store.frame.outer)
}

tess.trait.frame <- trait.effect.out.vote(dta=tess.candidate.features,candidate.trait=tess.independent.vars)

tess.trait.frame$variable.level <- c('Party: Co-Partisan','Gender: Female','Profession: Sales','Profession: Doctor','Profession: Surgeon','Profession: Professor','Profession: Business owner','Profession: High school teacher','Profession: Farmer','Profession: Lawyer','Profession: Rancher','Profession: Corporate executive','Profession: Attorney','Issue Agreement: Trade','Issue Agreement: Education','Frame Agreement: Trade','Frame Agreement: Education')

tess.trait.frame <- tess.trait.frame[order(tess.trait.frame$effect),]
tess.trait.frame$highlight <- NA
tess.trait.frame$highlight <- ifelse(tess.trait.frame$variable.type %in% c('trade.frame.agree','education.frame.agree'), 1, 0)

pdf(file="tess-candidatepreferences.pdf",height=6,width=8)
par(mar=c(4,14,2,2))
plot(y=1:dim(tess.trait.frame)[1],x=tess.trait.frame$effect,pch=16,ylab='',yaxt='n',xlim=c(-.05,.3),xlab='Effect of Feature on Pr(Prefer Candidate)',type='n')
abline(v=0,col='gray50')
axis(side=2,at=which(tess.trait.frame$highlight==0),labels=tess.trait.frame$variable.level[which(tess.trait.frame$highlight==0)],las=1,col.axis='gray50')
axis(side=2,at=which(tess.trait.frame$highlight==1),labels=tess.trait.frame$variable.level[which(tess.trait.frame$highlight==1)],las=1,font=2)

segments(x0=rep(-.5,dim(tess.trait.frame)[1]),x1=rep(.5,dim(tess.trait.frame)[1]),y0=1:dim(tess.trait.frame)[1],col='gray50',lty=2,lwd=.5)
segments(x0=tess.trait.frame$effect.lower.ci,x1=tess.trait.frame$effect.upper.ci,y0=1:dim(tess.trait.frame)[1],lwd=2)
points(x=tess.trait.frame$effect[which(tess.trait.frame$highlight==0)],y=which(tess.trait.frame$highlight==0),col='gray50',pch=16)
segments(x0=tess.trait.frame$effect.lower.ci[which(tess.trait.frame$highlight==0)],x1=tess.trait.frame$effect.upper.ci[which(tess.trait.frame$highlight==0)],y0=which(tess.trait.frame$highlight==0),lwd=2,col='gray50')

points(x=tess.trait.frame$effect[which(tess.trait.frame$highlight==1)],y=which(tess.trait.frame$highlight==1),pch=16)
segments(x0=tess.trait.frame$effect.lower.ci[which(tess.trait.frame$highlight==1)],x1=tess.trait.frame$effect.upper.ci[which(tess.trait.frame$highlight==1)],y0=which(tess.trait.frame$highlight==1),lwd=2)
segments(x0=c(-5,-5),x1=c(5,5),y0=which(tess.trait.frame$highlight==1),lwd=.5,lty=2)
dev.off()

#Mturk (Study 1)
load('mturk.candidate.features.RData')

mturk.independent.vars <- c('copartisan','gender.value','profession.value','religion.value','age.value','abortion.frame.agree','education.frame.agree','immigration.frame.agree','marriage.frame.agree','security.frame.agree','spending.frame.agree','trade.frame.agree','abortion.issue.agree','education.issue.agree','immigration.issue.agree','marriage.issue.agree','security.issue.agree','spending.issue.agree','trade.issue.agree')

mturk.candidate.features$profession.value <- relevel(x=mturk.candidate.features$profession.value,ref='Agriculture')
mturk.candidate.features$religion.value <- relevel(x=mturk.candidate.features$religion.value,ref='Protestant')
mturk.candidate.features$age.value <- relevel(x=mturk.candidate.features$age.value,ref="60's")
mturk.candidate.features$gender.value <- relevel(x=mturk.candidate.features$gender.value,ref="Male")

mturk.trait.frame <- trait.effect.out.vote(dta=mturk.candidate.features,candidate.trait=mturk.independent.vars)

mturk.trait.frame$variable.level <- c('Party: Co-Partisan','Gender: Female','Profession: Legal','Profession: Business','Profession: Sales','Profession: Medical','Profession: Education','Religion: Catholic','Religion: Evangelical Protestant','Religion: None Reported',"Age: 30's","Age: 40's","Age: 50's","Age: 70's",'Frame Agree: Abortion','Frame Agree: Education','Frame Agree: Immigration','Frame Agree: Marriage','Frame Agree: Security','Frame Agree: Spending','Frame Agree: Trade','Issue Agree: Abortion','Issue Agree: Education','Issue Agree: Immigration','Issue Agree: Marriage','Issue Agree: Security','Issue Agree: Spending','Issue Agree: Trade')

mturk.trait.frame <- mturk.trait.frame[order(mturk.trait.frame$effect),]
mturk.trait.frame$highlight <- NA
mturk.trait.frame$highlight <- ifelse(mturk.trait.frame$variable.type %in% c('abortion.frame.agree','education.frame.agree','immigration.frame.agree','marriage.frame.agree','security.frame.agree','spending.frame.agree','trade.frame.agree'), 1, 0)

pdf(file="mturk-candidatepreferences.pdf",height=6,width=8)
par(mar=c(4,14,2,2))
plot(y=1:dim(mturk.trait.frame)[1],x=mturk.trait.frame$effect,pch=16,ylab='',yaxt='n',xlim=c(-.05,.60),xlab='Effect of Feature on Pr(Prefer Candidate)',type='n')
abline(v=0,col='gray80')
axis(side=2,at=which(mturk.trait.frame$highlight==0),labels=mturk.trait.frame$variable.level[which(mturk.trait.frame$highlight==0)],las=1,col.axis='gray50')
axis(side=2,at=which(mturk.trait.frame$highlight==1),labels=mturk.trait.frame$variable.level[which(mturk.trait.frame$highlight==1)],las=1,font=2)

segments(x0=rep(-5,dim(mturk.trait.frame)[1]),x1=rep(5,dim(mturk.trait.frame)[1]),y0=1:dim(mturk.trait.frame)[1],col='gray50',lty=2,lwd=.5)
segments(x0=mturk.trait.frame$effect.lower.ci,x1=mturk.trait.frame$effect.upper.ci,y0=1:dim(mturk.trait.frame)[1],lwd=2)
points(x=mturk.trait.frame$effect[which(mturk.trait.frame$highlight==0)],y=which(mturk.trait.frame$highlight==0),col='gray50',pch=16)
segments(x0=mturk.trait.frame$effect.lower.ci[which(mturk.trait.frame$highlight==0)],x1=mturk.trait.frame$effect.upper.ci[which(mturk.trait.frame$highlight==0)],y0=which(mturk.trait.frame$highlight==0),lwd=2,col='gray50')

points(x=mturk.trait.frame$effect[which(mturk.trait.frame$highlight==1)],y=which(mturk.trait.frame$highlight==1),pch=16)
segments(x0=mturk.trait.frame$effect.lower.ci[which(mturk.trait.frame$highlight==1)],x1=mturk.trait.frame$effect.upper.ci[which(mturk.trait.frame$highlight==1)],y0=which(mturk.trait.frame$highlight==1),lwd=2)
segments(x0=c(-5,-5),x1=c(5,5),y0=which(mturk.trait.frame$highlight==1),lwd=.5,lty=2)
dev.off()

#Qualtrics (Study 2)
load('qualtrics.candidate.features.RData')

qualtrics.independent.vars <- c('copartisan','gender.value','profession.value','religion.value','age.value','education.frame.agree','trade.frame.agree','education.issue.agree','trade.issue.agree')

qualtrics.candidate.features$profession.value <- relevel(x=qualtrics.candidate.features$profession.value,ref='Car dealer')
qualtrics.candidate.features$religion.value <- relevel(x=qualtrics.candidate.features$religion.value,ref='Evangelical Protestant')
qualtrics.candidate.features$age.value <- relevel(x=factor(qualtrics.candidate.features$age.value),ref="70's")

qualtrics.trait.frame <- trait.effect.out.vote(dta=qualtrics.candidate.features,candidate.trait=qualtrics.independent.vars)

qualtrics.trait.frame$variable.level <- c('Party: Co-Partisan','Gender: Male','Profession: Attorney','Profession: Business owner','Profession: Corporate executive','Profession: Doctor','Profession: Farmer','Profession: High school teacher','Profession: Lawyer','Profession: Professor','Profession: Rancher','Profession: Sales','Profession: Surgeon','Religion: Catholic','Religion: None Reported','Religion: Protestant',"Age: 30's","Age: 40's","Age: 50's","Age: 60's","Frame Agree: Education","Frame Agree: Trade","Issue Agree: Education","Issue Agree: Trade")

qualtrics.trait.frame <- qualtrics.trait.frame[order(qualtrics.trait.frame$effect),]
qualtrics.trait.frame$highlight <- NA
qualtrics.trait.frame$highlight <- ifelse(qualtrics.trait.frame$variable.type %in% c('education.frame.agree','trade.frame.agree'), 1, 0)

#Visualization
pdf(file="qualtrics-candidatepreferences.pdf",height=6,width=8)
par(mar=c(4,14,2,2))
plot(y=1:dim(qualtrics.trait.frame)[1],x=qualtrics.trait.frame$effect,pch=16,ylab='',yaxt='n',xlim=c(-.1,.40),xlab='Effect of Feature on Pr(Prefer Candidate)',type='n')
abline(v=0,col='gray80')
axis(side=2,at=which(qualtrics.trait.frame$highlight==0),labels=qualtrics.trait.frame$variable.level[which(qualtrics.trait.frame$highlight==0)],las=1,col.axis='gray50')
axis(side=2,at=which(qualtrics.trait.frame$highlight==1),labels=qualtrics.trait.frame$variable.level[which(qualtrics.trait.frame$highlight==1)],las=1,font=2)

segments(x0=rep(-5,dim(qualtrics.trait.frame)[1]),x1=rep(5,dim(qualtrics.trait.frame)[1]),y0=1:dim(qualtrics.trait.frame)[1],col='gray50',lty=2,lwd=.5)
segments(x0=qualtrics.trait.frame$effect.lower.ci,x1=qualtrics.trait.frame$effect.upper.ci,y0=1:dim(qualtrics.trait.frame)[1],lwd=2)
points(x=qualtrics.trait.frame$effect[which(qualtrics.trait.frame$highlight==0)],y=which(qualtrics.trait.frame$highlight==0),col='gray50',pch=16)
segments(x0=qualtrics.trait.frame$effect.lower.ci[which(qualtrics.trait.frame$highlight==0)],x1=qualtrics.trait.frame$effect.upper.ci[which(qualtrics.trait.frame$highlight==0)],y0=which(qualtrics.trait.frame$highlight==0),lwd=2,col='gray50')

points(x=qualtrics.trait.frame$effect[which(qualtrics.trait.frame$highlight==1)],y=which(qualtrics.trait.frame$highlight==1),pch=16)
segments(x0=qualtrics.trait.frame$effect.lower.ci[which(qualtrics.trait.frame$highlight==1)],x1=qualtrics.trait.frame$effect.upper.ci[which(qualtrics.trait.frame$highlight==1)],y0=which(qualtrics.trait.frame$highlight==1),lwd=2)
segments(x0=c(-5,-5),x1=c(5,5),y0=which(qualtrics.trait.frame$highlight==1),lwd=.5,lty=2)
dev.off()

######
#Estimating Consequences of Issue Primes
######

ed.frame.agreement.by.prime <- lm(candidate.selected ~ education.frame.agree + education.prime + education.frame.agree*education.prime,data=tess.candidate.features)
ed.frame.agreement.by.prime <- fit.w.robust(ed.frame.agreement.by.prime,cluster.var='id',dta=tess.candidate.features)

ed.unprimed.point <- ed.frame.agreement.by.prime$coefficients[2]
ed.primed.point <- ed.frame.agreement.by.prime$coefficients[2] + ed.frame.agreement.by.prime$coefficients[4]
ed.diff.point <- ed.frame.agreement.by.prime$coefficients[4]

ed.unprimed.se <- sqrt(diag(ed.frame.agreement.by.prime$se)[2])
ed.primed.se <- sqrt(diag(ed.frame.agreement.by.prime$se)[2] + diag(ed.frame.agreement.by.prime$se)[4] + 2*ed.frame.agreement.by.prime$se[2,4])
ed.diff.se <- sqrt(diag(ed.frame.agreement.by.prime$se)[4])

ed.prime.coefs <- c(ed.diff.point,ed.unprimed.point,ed.primed.point)
ed.prime.ses <- c(ed.diff.se,ed.unprimed.se,ed.primed.se)
ed.prime.upper <- ed.prime.coefs + 2*ed.prime.ses
ed.prime.lower <- ed.prime.coefs - 2*ed.prime.ses

trade.frame.agreement.by.prime <- lm(candidate.selected ~ trade.frame.agree + trade.prime + trade.frame.agree*trade.prime,data=tess.candidate.features)
trade.frame.agreement.by.prime <- fit.w.robust(trade.frame.agreement.by.prime,cluster.var='id',dta=tess.candidate.features)

trade.unprimed.point <- trade.frame.agreement.by.prime$coefficients[2]
trade.primed.point <- trade.frame.agreement.by.prime$coefficients[2] + trade.frame.agreement.by.prime$coefficients[4]
trade.diff.point <- trade.frame.agreement.by.prime$coefficients[4]

trade.unprimed.se <- sqrt(diag(trade.frame.agreement.by.prime$se)[2])
trade.primed.se <- sqrt(diag(trade.frame.agreement.by.prime$se)[2] + diag(trade.frame.agreement.by.prime$se)[4] + 2*trade.frame.agreement.by.prime$se[2,4])
trade.diff.se <- sqrt(diag(trade.frame.agreement.by.prime$se)[4])

trade.prime.coefs <- c(trade.diff.point,trade.unprimed.point,trade.primed.point)
trade.prime.ses <- c(trade.diff.se,trade.unprimed.se,trade.primed.se)
trade.prime.upper <- trade.prime.coefs + 2*trade.prime.ses
trade.prime.lower <- trade.prime.coefs - 2*trade.prime.ses

pdf(file="primingcomparison.pdf",height=3.5,width=10.5)
par(mfrow=c(1,2),mar=c(4,5,2,1.5))
plot(y=1:3,x=ed.prime.coefs,pch=16,yaxt='n',xlim=c(-.045,.08),ylab='',main="Education",xlab="Effect of Frame on Candidate Preferences",ylim=c(.9,3.1))
abline(v=0,lty=2)
segments(y0=1:3,x0=ed.prime.lower,x1=ed.prime.upper,lwd=2)
axis(side=2,at=1:3,labels=c('Difference','Unprimed','Primed'),las=1)

plot(y=1:3,x=trade.prime.coefs,pch=16,yaxt='n',xlim=c(-.045,.08),ylab='',main="Trade",xlab="Effect of Frame on Candidate Preferences",ylim=c(.9,3.1))
abline(v=0,lty=2)
segments(y0=1:3,x0=trade.prime.lower,x1=trade.prime.upper,lwd=2)
axis(side=2,at=1:3,labels=c('Difference','Unprimed','Primed'),las=1)
dev.off()

#Manipulation Check of Prime on self-reported Importance

prime.frame <- unique(tess.candidate.features[,c('id','education.prime','trade.prime','top.issue.priority.trade','top.issue.priority.education')])

trade.priority <- lm(top.issue.priority.trade ~ trade.prime,data=prime.frame)
education.priority <- lm(top.issue.priority.education ~ education.prime,data=prime.frame)
apsrtable(education.priority,trade.priority,model.names=c('Education Policy Top Priority','Trade Policy Top Priority'),caption="Issue Importance by Priming Condition")




#############################
#############################
#############################
#############################End of in-text results
#############################
#############################
#############################




######
##Robustness Checks / Appendix Materials
######

######
##Estimating Framing Effect Carry-Over To Vote By Candidate Choice Number
######

framing.vote.combined$issuebysurveybynumber <- paste(framing.vote.combined$issuebysurvey,'-',framing.vote.combined$choice.number,sep='')
issue.bynum.list <- unique(framing.vote.combined$issuebysurveybynumber)

framing.effect.out.vote.bynum <- function(issue.num){
	frame.mod <- lm(candidate.selected~frame.agree,data=framing.vote.combined[framing.vote.combined$issuebysurveybynumber==issue.num,])
	frame.mod <- fit.w.robust(frame.mod,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurveybynumber==issue.num,])
	return(c(frame.mod$coefficients[2],sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]-2*sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]+2*sqrt(frame.mod$se[2,2])))
}

framing.effect.vote.out.bynum <- as.data.frame(t(sapply(X=issue.bynum.list,FUN=framing.effect.out.vote.bynum)))
names(framing.effect.vote.out.bynum) <- c('framing.effect.vote.point','framing.effect.vote.se','framing.effect.vote.lower.ci','framing.effect.vote.upper.ci')
framing.effect.vote.out.bynum$order <- unlist(lapply(X=strsplit(x=rownames(framing.effect.vote.out.bynum),split='-',fixed=TRUE),FUN='[[',3))
framing.effect.vote.out.bynum$sample <- unlist(lapply(X=strsplit(x=rownames(framing.effect.vote.out.bynum),split='-',fixed=TRUE),FUN='[[',2))
framing.effect.vote.out.bynum$issue <- unlist(lapply(X=strsplit(x=rownames(framing.effect.vote.out.bynum),split='-',fixed=TRUE),FUN='[[',1))
framing.effect.vote.out.bynum$study <- NA
framing.effect.vote.out.bynum$study[which(framing.effect.vote.out.bynum$sample=="mturk")] <- framing.effect.vote.out.bynum$study[which(framing.effect.vote.out.bynum$sample=="mturk")] <- 'Study 1'
framing.effect.vote.out.bynum$study[which(framing.effect.vote.out.bynum$sample=="qualtrics")] <- framing.effect.vote.out.bynum$study[which(framing.effect.vote.out.bynum$sample=="qualtrics")] <- 'Study 2'
framing.effect.vote.out.bynum$study[which(framing.effect.vote.out.bynum$sample=="tess")] <- framing.effect.vote.out.bynum$study[which(framing.effect.vote.out.bynum$sample=="tess")] <- 'Study 3'

framing.effect.vote.out.bynum <- framing.effect.vote.out.bynum[order(framing.effect.vote.out.bynum$study,framing.effect.vote.out.bynum$issue,framing.effect.vote.out.bynum$order),]

framing.effect.vote.out.bynum.education <- subset(framing.effect.vote.out.bynum,framing.effect.vote.out.bynum$issue=="Education Policy")
framing.effect.vote.out.bynum.trade <- subset(framing.effect.vote.out.bynum,framing.effect.vote.out.bynum$issue=="Trade Policy")

framing.effect.vote.out.bynum.study1 <- subset(framing.effect.vote.out.bynum,framing.effect.vote.out.bynum$study=="Study 1")
framing.effect.vote.out.bynum.study2 <- subset(framing.effect.vote.out.bynum,framing.effect.vote.out.bynum$study=="Study 2")
framing.effect.vote.out.bynum.study3 <- subset(framing.effect.vote.out.bynum,framing.effect.vote.out.bynum$study=="Study 3")

#Plot for two most powerful frames examined across the studies
pdf(file="frame-issuevoting-bychoiceorder.pdf",height=6,width=10)
par(mar=c(4,4.75,4,4),mfrow=c(1,2))
plot(x=framing.effect.vote.out.bynum.education$framing.effect.vote.point,y=length(framing.effect.vote.out.bynum.education$framing.effect.vote.point):1,xlim=c(-.125,.3),pch=16,yaxt='n',ylab='',xlab='Effect of Issue Frame on Vote Choice',main="Education")
abline(v=0,lty=2,col='gray80')
axis(side=4,at=length(framing.effect.vote.out.bynum.education$framing.effect.vote.point):1,labels=framing.effect.vote.out.bynum.education$order,las=1)
segments(x0=framing.effect.vote.out.bynum.education$framing.effect.vote.lower.ci,x1=framing.effect.vote.out.bynum.education$framing.effect.vote.upper.ci,y0=length(framing.effect.vote.out.bynum.education$framing.effect.vote.point):1,lwd=2)
segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(4.5,8.5),lwd=2)
axis(side=2,at=c(2.5,6.5,12.5),labels=c('Study 3','Study 2','Study 1'),las=1)

plot(x=framing.effect.vote.out.bynum.trade$framing.effect.vote.point,y=length(framing.effect.vote.out.bynum.trade$framing.effect.vote.point):1,xlim=c(-.125,.3),pch=16,yaxt='n',ylab='',xlab='Effect of Issue Frame on Vote Choice',main="Trade")
abline(v=0,lty=2,col='gray80')
axis(side=4,at=length(framing.effect.vote.out.bynum.trade$framing.effect.vote.point):1,labels=framing.effect.vote.out.bynum.trade$order,las=1)
axis(side=2,at=c(2.5,6.5,12.5),labels=c('Study 3','Study 2','Study 1'),las=1)

segments(x0=framing.effect.vote.out.bynum.trade$framing.effect.vote.lower.ci,x1=framing.effect.vote.out.bynum.trade$framing.effect.vote.upper.ci,y0=length(framing.effect.vote.out.bynum.trade$framing.effect.vote.point):1,lwd=2)
segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(4.5,8.5),lwd=2)
dev.off()

######
##Estimating Issue Agreement Effect By Candidate Choice Number
######

framing.vote.combined$issuebysurveybynumber <- paste(framing.vote.combined$issuebysurvey,'-',framing.vote.combined$choice.number,sep='')
issue.bynum.list <- unique(framing.vote.combined$issuebysurveybynumber)

issue.effect.out.vote.bynum <- function(issue.num){
	frame.mod <- lm(candidate.selected~issue.agree,data=framing.vote.combined[framing.vote.combined$issuebysurveybynumber==issue.num,])
	frame.mod <- fit.w.robust(frame.mod,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurveybynumber==issue.num,])
	return(c(frame.mod$coefficients[2],sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]-2*sqrt(frame.mod$se[2,2]),frame.mod$coefficients[2]+2*sqrt(frame.mod$se[2,2])))
}

issue.effect.vote.out.bynum <- as.data.frame(t(sapply(X=issue.bynum.list,FUN=issue.effect.out.vote.bynum)))
names(issue.effect.vote.out.bynum) <- c('framing.effect.vote.point','framing.effect.vote.se','framing.effect.vote.lower.ci','framing.effect.vote.upper.ci')
issue.effect.vote.out.bynum$order <- unlist(lapply(X=strsplit(x=rownames(issue.effect.vote.out.bynum),split='-',fixed=TRUE),FUN='[[',3))
issue.effect.vote.out.bynum$sample <- unlist(lapply(X=strsplit(x=rownames(issue.effect.vote.out.bynum),split='-',fixed=TRUE),FUN='[[',2))
issue.effect.vote.out.bynum$issue <- unlist(lapply(X=strsplit(x=rownames(issue.effect.vote.out.bynum),split='-',fixed=TRUE),FUN='[[',1))
issue.effect.vote.out.bynum$study <- NA
issue.effect.vote.out.bynum$study[which(issue.effect.vote.out.bynum$sample=="mturk")] <- issue.effect.vote.out.bynum$study[which(issue.effect.vote.out.bynum$sample=="mturk")] <- 'Study 1'
issue.effect.vote.out.bynum$study[which(issue.effect.vote.out.bynum$sample=="qualtrics")] <- issue.effect.vote.out.bynum$study[which(issue.effect.vote.out.bynum$sample=="qualtrics")] <- 'Study 2'
issue.effect.vote.out.bynum$study[which(issue.effect.vote.out.bynum$sample=="tess")] <- issue.effect.vote.out.bynum$study[which(issue.effect.vote.out.bynum$sample=="tess")] <- 'Study 3'

issue.effect.vote.out.bynum <- issue.effect.vote.out.bynum[order(issue.effect.vote.out.bynum$study,issue.effect.vote.out.bynum$issue,issue.effect.vote.out.bynum$order),]

issue.effect.vote.out.bynum.education <- subset(issue.effect.vote.out.bynum,issue.effect.vote.out.bynum$issue=="Education Policy")
issue.effect.vote.out.bynum.trade <- subset(issue.effect.vote.out.bynum,issue.effect.vote.out.bynum$issue=="Trade Policy")

issue.effect.vote.out.bynum.study1 <- subset(issue.effect.vote.out.bynum,issue.effect.vote.out.bynum$study=="Study 1")
issue.effect.vote.out.bynum.study2 <- subset(issue.effect.vote.out.bynum,issue.effect.vote.out.bynum$study=="Study 2")
issue.effect.vote.out.bynum.study3 <- subset(issue.effect.vote.out.bynum,issue.effect.vote.out.bynum$study=="Study 3")

#Plot for two most powerful frames examined across the studies
pdf(file="issue-issuevoting-bychoiceorder.pdf",height=6,width=10)
par(mar=c(4,4.75,4,4),mfrow=c(1,2))
plot(x=issue.effect.vote.out.bynum.education$framing.effect.vote.point,y=length(issue.effect.vote.out.bynum.education$framing.effect.vote.point):1,xlim=c(0,.5),pch=16,yaxt='n',ylab='',xlab='Effect of Issue Agreement on Vote Choice',main="Education")
abline(v=0,lty=2,col='gray80')
axis(side=4,at=length(issue.effect.vote.out.bynum.education$framing.effect.vote.point):1,labels=issue.effect.vote.out.bynum.education$order,las=1)
segments(x0=issue.effect.vote.out.bynum.education$framing.effect.vote.lower.ci,x1=issue.effect.vote.out.bynum.education$framing.effect.vote.upper.ci,y0=length(issue.effect.vote.out.bynum.education$framing.effect.vote.point):1,lwd=2)
segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(4.5,8.5),lwd=2)
axis(side=2,at=c(2.5,6.5,12.5),labels=c('Study 3','Study 2','Study 1'),las=1)

plot(x=issue.effect.vote.out.bynum.trade$framing.effect.vote.point,y=length(issue.effect.vote.out.bynum.trade$framing.effect.vote.point):1,xlim=c(0,.5),pch=16,yaxt='n',ylab='',xlab='Effect of Issue Agreement on Vote Choice',main="Trade")
abline(v=0,lty=2,col='gray80')
axis(side=4,at=length(issue.effect.vote.out.bynum.trade$framing.effect.vote.point):1,labels=issue.effect.vote.out.bynum.trade$order,las=1)
axis(side=2,at=c(2.5,6.5,12.5),labels=c('Study 3','Study 2','Study 1'),las=1)

segments(x0=issue.effect.vote.out.bynum.trade$framing.effect.vote.lower.ci,x1=issue.effect.vote.out.bynum.trade$framing.effect.vote.upper.ci,y0=length(issue.effect.vote.out.bynum.trade$framing.effect.vote.point):1,lwd=2)
segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(4.5,8.5),lwd=2)
dev.off()

######
##Testing for Opinion Change Based on Opinions Offered in Co-Partisan Candidate Profiles
######

initial.conjoint <- subset(tess.candidate.features,tess.candidate.features$choice.number=="choice1")

initial.conjoint$copartisan.stance.trade <- NA
initial.conjoint$copartisan.stance.trade[which(initial.conjoint$copartisan==1)] <- initial.conjoint$candidate.trade[which(initial.conjoint$copartisan==1)]

initial.conjoint$copartisan.stance.education <- NA
initial.conjoint$copartisan.stance.education[which(initial.conjoint$copartisan==1)] <- initial.conjoint$candidate.education[which(initial.conjoint$copartisan==1)]

initial.conjoint <- na.omit(unique(initial.conjoint[,c('id','copartisan.stance.trade','copartisan.stance.education')]))

id.length <- function(x){
	return(length(initial.conjoint$id[which(initial.conjoint$id==x)]))
}
id.length.out <- sapply(X=unique(initial.conjoint$id),FUN=id.length)
toss.ids <- unique(initial.conjoint$id)[which(id.length.out > 1)]

initial.conjoint <- subset(initial.conjoint,!(initial.conjoint$id %in% toss.ids))
names(initial.conjoint) <- c('id','prior.copartisan.stance.trade','prior.copartisan.stance.education')

second.conjoint <- subset(tess.candidate.features,tess.candidate.features$choice.number=="choice2")
second.conjoint <- merge(second.conjoint,initial.conjoint,by=c('id'),all.x=TRUE)

second.conjoint$trade.agree.prior <- ifelse(second.conjoint$candidate.trade==second.conjoint$prior.copartisan.stance.trade, 1, 0)
second.conjoint$education.agree.prior <- ifelse(second.conjoint$candidate.education==second.conjoint$prior.copartisan.stance.education, 1, 0)

trade.adjustment <- lm(candidate.selected ~ trade.issue.agree*trade.agree.prior,data=second.conjoint)
trade.adjustment  <- fit.w.robust(trade.adjustment,cluster.var='id',dta=second.conjoint)
names(trade.adjustment$coefficients) <- c("(Intercept)","Issue Agree","Prior Co-Partisan Agree","Issue Agree*Prior Co-Partisan Agree")

education.adjustment <- lm(candidate.selected ~ education.issue.agree*education.agree.prior,data=second.conjoint)
education.adjustment  <- fit.w.robust(education.adjustment,cluster.var='id',dta=second.conjoint)
names(education.adjustment$coefficients) <- c("(Intercept)","Issue Agree","Prior Co-Partisan Agree","Issue Agree*Prior Co-Partisan Agree")

apsrtable(education.adjustment,trade.adjustment,model.names=c("Education","Trade"),se=c("robust"))

######
##Primary Election v. General Election
######

framing.effect.out.vote.subset.party <- function(issue){
	frame.mod.primary <- lm(candidate.selected~frame.agree,data=framing.vote.combined[framing.vote.combined$issuebysurvey==issue & framing.vote.combined$party.contrast==0,])
	frame.mod.primary <- fit.w.robust(frame.mod.primary,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurvey==issue & framing.vote.combined$party.contrast==0,])
	
	frame.mod.general <- lm(candidate.selected~frame.agree,data=framing.vote.combined[framing.vote.combined$issuebysurvey==issue & framing.vote.combined$party.contrast==1,])
	frame.mod.general <- fit.w.robust(frame.mod.general,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurvey==issue & framing.vote.combined$party.contrast==1,])
		return(c(frame.mod.primary$coefficients[2],sqrt(frame.mod.primary$se[2,2]),frame.mod.primary$coefficients[2]-2*sqrt(frame.mod.primary$se[2,2]),frame.mod.primary$coefficients[2]+2*sqrt(frame.mod.primary$se[2,2]),frame.mod.general$coefficients[2],sqrt(frame.mod.general$se[2,2]),frame.mod.general$coefficients[2]-2*sqrt(frame.mod.general$se[2,2]),frame.mod.general$coefficients[2]+2*sqrt(frame.mod.general$se[2,2])))
}

issue.order.appendix <- c("Education Policy-mturk","Trade Policy-mturk","Security Policy-mturk","Marriage Policy-mturk","Spending Policy-mturk","Immigration Policy-mturk","Abortion Policy-mturk","Trade Policy-qualtrics","Education Policy-qualtrics","Education Policy-tess","Trade Policy-tess")

framing.effect.vote.out.electiontype <- as.data.frame(t(sapply(X=issue.order.appendix,FUN=framing.effect.out.vote.subset.party)))
names(framing.effect.vote.out.electiontype) <- c('framing.effect.vote.point.primary','framing.effect.vote.se.primary','framing.effect.vote.lower.ci.primary','framing.effect.vote.upper.ci.primary','framing.effect.vote.point.general','framing.effect.vote.se.general','framing.effect.vote.lower.ci.general','framing.effect.vote.upper.ci.general')

plot.names <- unlist(lapply(X=strsplit(x=rownames(framing.effect.vote.out.electiontype),split=" "),FUN="[[",1))

pdf(height=8, width=6, file="general-primary-carryover.pdf")
par(mar=c(4,5,2,4))
plot(y=dim(framing.effect.vote.out.electiontype)[1]:1-.15,x=framing.effect.vote.out.electiontype[,1],ylim=c(.9,11.1),pch=16,yaxt='n',xlim=c(-.08,.15),ylab='',xlab="Framing Effect on Pr(Select Candidate)")
points(y=dim(framing.effect.vote.out.electiontype)[1]:1+.15,x=framing.effect.vote.out.electiontype[,5],pch=16,col='gray60')

axis(side=2,at=dim(framing.effect.vote.out.electiontype)[1]:1,las=1,labels=plot.names,tick=FALSE,line=-.75)
axis(side=4,at=c(1.5,3.5,8),las=1,labels=c("Study 3","Study 2","Study 1"),tick=FALSE,line=-.75)

segments(x0=rep(-.5,times=length(combined.plot.frame$framing.effect.opinion.point)),x1=rep(.5,times=length(combined.plot.frame$framing.effect.opinion.point)),y0=1:length(combined.plot.frame$framing.effect.opinion.point)+.5,lwd=.5,col='gray70')
segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(2.5,4.5),lwd=2)

segments(x0=framing.effect.vote.out.electiontype[,3],x1=framing.effect.vote.out.electiontype[,4],y0=dim(framing.effect.vote.out.electiontype)[1]:1-.15,lwd=2)
segments(x0=framing.effect.vote.out.electiontype[,7],x1=framing.effect.vote.out.electiontype[,8],y0=dim(framing.effect.vote.out.electiontype)[1]:1+.15,lwd=2,col='gray60')
text(y=8.15,x=.12,label='Same Party',cex=.68)
text(y=7.85,x=.12,label='Opposing Parties',cex=.68)
dev.off()

######
##Removing Profiles Where Candidates Agree on an Issue
######

framing.effect.out.vote.subset.issuecontrast <- function(issue){
	frame.mod.contrast <- lm(candidate.selected~frame.agree,data=framing.vote.combined[framing.vote.combined$issuebysurvey==issue & framing.vote.combined$issue.contrast==1,])
	frame.mod.contrast <- fit.w.robust(frame.mod.contrast,cluster.var="id",dta=framing.vote.combined[framing.vote.combined$issuebysurvey==issue & framing.vote.combined$issue.contrast==1,])
	
	return(c(frame.mod.contrast$coefficients[2],sqrt(frame.mod.contrast$se[2,2]),frame.mod.contrast$coefficients[2]-2*sqrt(frame.mod.contrast$se[2,2]),frame.mod.contrast$coefficients[2]+2*sqrt(frame.mod.contrast$se[2,2])))
}

issue.order.appendix.2 <- c("Education Policy-mturk","Security Policy-mturk","Trade Policy-mturk","Marriage Policy-mturk","Spending Policy-mturk","Immigration Policy-mturk","Abortion Policy-mturk","Trade Policy-qualtrics","Education Policy-qualtrics","Education Policy-tess","Trade Policy-tess")

framing.effect.vote.out.issuecontrast <- as.data.frame(t(sapply(X=issue.order.appendix.2,FUN=framing.effect.out.vote.subset.issuecontrast)))
names(framing.effect.vote.out.issuecontrast) <- c('framing.effect.vote.point.issuecontrast','framing.effect.vote.se.issuecontrast','framing.effect.vote.lower.ci.issuecontrast','framing.effect.vote.upper.ci.issuecontrast')

pdf(height=8, width=6, file="issuecontrast-only.pdf")
par(mar=c(4,5,2,4))
plot(y=dim(framing.effect.vote.out.issuecontrast)[1]:1,x=framing.effect.vote.out.issuecontrast[,1],ylim=c(.9,11.1),pch=16,yaxt='n',xlim=c(-.1,.175),ylab='',xlab="Framing Effect on Pr(Select Candidate)")

axis(side=2,at=dim(framing.effect.vote.out.issuecontrast)[1]:1,las=1,labels=plot.names,tick=FALSE,line=-.75)
axis(side=4,at=c(1.5,3.5,8),las=1,labels=c("Study 3","Study 2","Study 1"),tick=FALSE,line=-.75)

segments(x0=rep(-.5,times=length(framing.effect.vote.out.issuecontrast$framing.effect.vote.point)),x1=rep(.5,times=length(framing.effect.vote.out.issuecontrast$framing.effect.vote.point)),y0=1:length(framing.effect.vote.out.issuecontrast$framing.effect.vote.point)+.5,lwd=.5,col='gray70')
segments(x0=rep(-.5,times=2),x1=rep(.5,times=2),y0=c(2.5,4.5),lwd=2)

segments(x0=framing.effect.vote.out.issuecontrast[,3],x1=framing.effect.vote.out.issuecontrast[,4],y0=dim(framing.effect.vote.out.issuecontrast)[1]:1,lwd=2)
abline(v=0,lty=2,col='gray60')
dev.off()

######
##IV Estimates - Pooled from S1/S2/S3
######

#Instrumented Issue Agreement Estimates
tess.iv.trade <- ivreg(candidate.selected ~ trade.issue.agree | trade.frame.agree,data=tess.candidate.features)
tess.iv.trade <- fit.w.robust(tess.iv.trade,cluster.var="id",dta=tess.candidate.features)

tess.iv.education <- ivreg(candidate.selected ~ education.issue.agree | education.frame.agree,data=tess.candidate.features)
tess.iv.education <- fit.w.robust(tess.iv.education,cluster.var="id",dta=tess.candidate.features)

qualtrics.iv.trade <- ivreg(candidate.selected ~ trade.issue.agree | trade.frame.agree,data=qualtrics.candidate.features)
qualtrics.iv.trade <- fit.w.robust(qualtrics.iv.trade,cluster.var="id",dta=qualtrics.candidate.features)

qualtrics.iv.education <- ivreg(candidate.selected ~ education.issue.agree | education.frame.agree,data=qualtrics.candidate.features)
qualtrics.iv.education <- fit.w.robust(qualtrics.iv.education,cluster.var="id",dta=qualtrics.candidate.features)

#Direct Agreement Estimates
tess.direct.trade <- lm(candidate.selected ~ trade.issue.agree,data=tess.candidate.features)
tess.direct.trade <- fit.w.robust(tess.direct.trade,cluster.var="id",dta=tess.candidate.features)

tess.direct.education <- lm(candidate.selected ~ education.issue.agree,data=tess.candidate.features)
tess.direct.education <- fit.w.robust(tess.direct.education,cluster.var="id",dta=tess.candidate.features)

qualtrics.direct.trade <- lm(candidate.selected ~ trade.issue.agree,data=qualtrics.candidate.features)
qualtrics.direct.trade <- fit.w.robust(qualtrics.direct.trade,cluster.var="id",dta=qualtrics.candidate.features)

qualtrics.direct.education <- lm(candidate.selected ~ education.issue.agree,data=qualtrics.candidate.features)
qualtrics.direct.education <- fit.w.robust(qualtrics.direct.education,cluster.var="id",dta=qualtrics.candidate.features)

education.direct.coefs <- c(tess.direct.education$coefficients[2],qualtrics.direct.education$coefficients[2])
education.direct.ses <- c(sqrt(tess.direct.education$se[2,2]),sqrt(qualtrics.direct.education$se[2,2]))

education.iv.coefs <- c(tess.iv.education$coefficients[2],qualtrics.iv.education$coefficients[2])
education.iv.ses <- c(sqrt(tess.iv.education$se[2,2]),sqrt(qualtrics.iv.education$se[2,2]))

trade.direct.coefs <- c(tess.direct.trade$coefficients[2],qualtrics.direct.trade$coefficients[2])
trade.direct.ses <- c(sqrt(tess.direct.trade$se[2,2]),sqrt(qualtrics.direct.trade$se[2,2]))

trade.iv.coefs <- c(tess.iv.trade$coefficients[2],qualtrics.iv.trade$coefficients[2])
trade.iv.ses <- c(sqrt(tess.iv.trade$se[2,2]),sqrt(qualtrics.iv.trade$se[2,2]))

pdf(file="ivcomparisons.pdf",height=4,width=8)
par(mfrow=c(1,2),mar=c(5,6.76,4,2))
plot(y=c(1.1,2.1),x=education.direct.coefs,main="Education",ylim=c(.8,2.2),xlim=c(0,.5),yaxt='n',ylab='',pch=16,xlab="Effect of Issue Agreement on
Pr(Select Candidate)")
points(y=c(.9,1.9),x=education.iv.coefs,pch=16)
axis(side=2,at=c(.9,1.1,1.9,2.1),labels=c('TESS IV','TESS Direct','Qualtrics IV','Qualtrics Direct'),las=1)
segments(y0=c(1.1,2.1),x0=education.direct.coefs+2*education.direct.ses,x1=education.direct.coefs-2*education.direct.ses,lwd=2)
segments(y0=c(.9,1.9),x0=education.iv.coefs+2*education.iv.ses,x1=education.iv.coefs-2*education.iv.ses,lwd=2)

plot(y=c(1.1,2.1),x=trade.direct.coefs,main="Trade",ylim=c(.8,2.2),xlim=c(0,.4),yaxt='n',ylab='',pch=16,xlab="Effect of Issue Agreement on
Pr(Select Candidate)")
points(y=c(.9,1.9),x=trade.iv.coefs,pch=16)
axis(side=2,at=c(.9,1.1,1.9,2.1),labels=c('TESS IV','TESS Direct','Qualtrics IV','Qualtrics Direct'),las=1)
segments(y0=c(1.1,2.1),x0=trade.direct.coefs+2*trade.direct.ses,x1=trade.direct.coefs-2*trade.direct.ses,lwd=2)
segments(y0=c(.9,1.9),x0=trade.iv.coefs+2*trade.iv.ses,x1=trade.iv.coefs-2*trade.iv.ses,lwd=2)
dev.off()

######
#Frame Strength and Issue Importance in Study 1
######
load('mturk.framing.opinion.RData')
mturk.framing.opinion$relative.importance.pos <- as.numeric(as.character(mapvalues(mturk.framing.opinion$relative.importance,from=c(1,2,3,4,5,6,7),to=c(7,6,5,4,3,2,1))))

relative.importance.cont <- lm(opinion ~ frame + relative.importance.pos + frame*relative.importance.pos + factor(issue) + factor(id), data=mturk.framing.opinion)
relative.importance.cont <- fit.w.robust(relative.importance.cont,cluster.var='id',dta=mturk.framing.opinion)

relative.importance.factor <-  lm(opinion ~ frame + factor(relative.importance.pos) + frame*factor(relative.importance.pos) + factor(issue) + factor(id), data=mturk.framing.opinion)
relative.importance.factor <- fit.w.robust(relative.importance.factor,cluster.var='id',dta=mturk.framing.opinion)

absolute.importance.cont <- lm(opinion ~ frame + importance + frame*importance + factor(issue) + factor(id), data=mturk.framing.opinion)
absolute.importance.cont <- fit.w.robust(absolute.importance.cont,cluster.var='id',dta=mturk.framing.opinion)

absolute.importance.factor <- lm(opinion ~ frame + factor(importance) + frame*factor(importance) + factor(issue) + factor(id), data=mturk.framing.opinion)
absolute.importance.factor <- fit.w.robust(absolute.importance.factor,cluster.var='id',dta=mturk.framing.opinion)

continuous.omit.coefs <- grep(pattern="id|issue",x=names(absolute.importance.cont$coefficients))
apsrtable(absolute.importance.cont,relative.importance.cont,omitcoef=continuous.omit.coefs,se=c("robust"),model.names=c("Importance","Relative Importance"))

factor.omit.coefs <- grep(pattern="id|issue",x=names(absolute.importance.factor$coefficients))
apsrtable(absolute.importance.factor,relative.importance.factor,omitcoef=factor.omit.coefs,se=c("robust"),model.names=c("Importance","Relative Importance"))

######
##Priming and Opinion Carryover in Study 2
######

qualtrics.candidate.features$trade.prime <- NA
qualtrics.candidate.features$trade.prime[which(qualtrics.candidate.features$education.prime==1)] <- 0
qualtrics.candidate.features$trade.prime[which(qualtrics.candidate.features$education.prime==0)] <- 1

ed.frame.agreement.by.prime.qual <- lm(candidate.selected ~ education.frame.agree + education.prime + education.frame.agree*education.prime,data=qualtrics.candidate.features)
ed.frame.agreement.by.prime.qual <- fit.w.robust(ed.frame.agreement.by.prime.qual,cluster.var='id',dta=qualtrics.candidate.features)

ed.unprimed.point.qual <- ed.frame.agreement.by.prime.qual$coefficients[2]
ed.primed.point.qual <- ed.frame.agreement.by.prime.qual$coefficients[2] + ed.frame.agreement.by.prime.qual$coefficients[4]
ed.diff.point.qual <- ed.frame.agreement.by.prime.qual$coefficients[4]

ed.unprimed.se.qual <- sqrt(diag(ed.frame.agreement.by.prime.qual$se)[2])
ed.primed.se.qual <- sqrt(diag(ed.frame.agreement.by.prime.qual$se)[2] + diag(ed.frame.agreement.by.prime.qual$se)[4] + 2*ed.frame.agreement.by.prime.qual$se[2,4])
ed.diff.se.qual <- sqrt(diag(ed.frame.agreement.by.prime.qual$se)[4])

ed.prime.coefs.qual <- c(ed.diff.point.qual,ed.unprimed.point.qual,ed.primed.point.qual)
ed.prime.ses.qual <- c(ed.diff.se.qual,ed.unprimed.se.qual,ed.primed.se.qual)
ed.prime.upper.qual <- ed.prime.coefs.qual + 2*ed.prime.ses.qual
ed.prime.lower.qual <- ed.prime.coefs.qual - 2*ed.prime.ses.qual

trade.frame.agreement.by.prime.qual <- lm(candidate.selected ~ trade.frame.agree + trade.prime + trade.frame.agree*trade.prime,data=qualtrics.candidate.features)
trade.frame.agreement.by.prime.qual <- fit.w.robust(trade.frame.agreement.by.prime.qual,cluster.var='id',dta=qualtrics.candidate.features)

trade.unprimed.point.qual <- trade.frame.agreement.by.prime.qual$coefficients[2]
trade.primed.point.qual <- trade.frame.agreement.by.prime.qual$coefficients[2] + trade.frame.agreement.by.prime.qual$coefficients[4]
trade.diff.point.qual <- trade.frame.agreement.by.prime.qual$coefficients[4]

trade.unprimed.se.qual <- sqrt(diag(trade.frame.agreement.by.prime.qual$se)[2])
trade.primed.se.qual <- sqrt(diag(trade.frame.agreement.by.prime.qual$se)[2] + diag(trade.frame.agreement.by.prime.qual$se)[4] + 2*trade.frame.agreement.by.prime.qual$se[2,4])
trade.diff.se.qual <- sqrt(diag(trade.frame.agreement.by.prime.qual$se)[4])

trade.prime.coefs.qual <- c(trade.diff.point.qual,trade.unprimed.point.qual,trade.primed.point.qual)
trade.prime.ses.qual <- c(trade.diff.se.qual,trade.unprimed.se.qual,trade.primed.se.qual)
trade.prime.upper.qual <- trade.prime.coefs.qual + 2*trade.prime.ses.qual
trade.prime.lower.qual <- trade.prime.coefs.qual - 2*trade.prime.ses.qual

pdf(file="primingcomparison-qualtrics.pdf",height=3.5,width=10.5)
par(mfrow=c(1,2),mar=c(4,5,2,1.5))
plot(y=1:3,x=ed.prime.coefs.qual,pch=16,yaxt='n',xlim=c(-.1,.12),ylab='',main="Education",xlab="Effect of Frame on Candidate Preferences",ylim=c(.9,3.1))
abline(v=0,lty=2)
segments(y0=1:3,x0=ed.prime.lower.qual,x1=ed.prime.upper.qual,lwd=2)
axis(side=2,at=1:3,labels=c('Difference','Unprimed','Primed'),las=1)

plot(y=1:3,x=trade.prime.coefs.qual,pch=16,yaxt='n',xlim=c(-.1,.12),ylab='',main="Trade",xlab="Effect of Frame on Candidate Preferences",ylim=c(.9,3.1))
abline(v=0,lty=2)
segments(y0=1:3,x0=trade.prime.lower.qual,x1=trade.prime.upper.qual,lwd=2)
axis(side=2,at=1:3,labels=c('Difference','Unprimed','Primed'),las=1)
dev.off()